package com.powerunion.extjs.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;

import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.pagination.IPagination;
import com.powerunion.datacollection.persistence.pagination.PageParameter;
import com.powerunion.datacollection.persistence.pagination.PageResult;
import com.powerunion.datacollection.persistence.pagination.PaginationFactory;
import com.powerunion.extjs.BasePara;
import com.powerunion.extjs.ListRange;
import com.powerunion.extjs.utils.Convert;

public abstract class DbDataLoader {
	protected BasePara paravo = null;
	protected int totalCount;
	//protected Session session = null;
	protected Convert convert = new Convert();
	protected Collection rs = null;
	protected ListRange range = null;
	
	public DbDataLoader(BasePara paravo){
		this.paravo = paravo;
	}
	
	public void init(){
		//this.session = HibernateSessionFactory.currentSession();
	}
	
	public abstract void wrapSql() throws Exception;
	public abstract void collectToMap();
	
	public void load() throws Exception{
		String sql = this.paravo.getSql();
		String type = this.paravo.getType();
		Object params = this.paravo.getParams();
		
		if(this.paravo.isPaging()){
			this.totalCount = this.getTotalCount(sql, params, type);
			//System.out.println("total:"+this.totalCount);
	    	rs = this.getPagingRecords(sql, params,type, this.paravo.getStart(), this.paravo.getLimit());
		}else{
			rs = this.getRecords(sql, params,type);
			this.totalCount = rs.size();
		}
	}
	
	public void run(){
		try{
			this.init();
			this.wrapSql();
			this.load();
			this.collectToMap();
		}
		catch (Exception e){
			System.out.println("获取数据失败！"+e.getMessage());
			e.printStackTrace();
		}
		
	}

	public int getTotalCount(String hql, Object params,String type) throws Exception {
		int total = 0;
		try {
			if(hql.indexOf(" group ")>0) hql = hql.replace(hql.substring(hql.indexOf("group")), "");
			if(hql.indexOf(" order by ")>0) hql = hql.replace(hql.substring(hql.indexOf("order by")), "");
			
			hql = "select count(1) as count " + hql.substring(hql.lastIndexOf("from"));
			QueryOperator query = new QueryOperator();
			query.setSql(hql);
			query = convert.getParams(query, params);
			query.access();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				if (rs.rowCount > 0) {
					total =rs.getFieldValueAsInteger("count").intValue();
				}
				rs.clearAll();
			}
			
		} catch (Exception e) {
			throw new Exception("get total error-->"+e.getMessage(),e.getCause());
		} 
		return total;
	}	
	
	public Collection getRecords(String sql, Object params,String type) throws Exception {
		Collection col = null;
		try {
			QueryOperator query = new QueryOperator();
			query = convert.getParams(query,  params);
			query.setSql(sql);
			query.access();
			if (query.resultSetAvailable()) {// 检查结果集是否可用
				// 获取并处理记录集
				col = query.getSqlResultSet();
			}
			
		} catch (Exception e) {
			System.out.println("error_sql:"+sql);
			throw new Exception("get all record error-->"+e.getMessage(),e.getCause());
		}
		return col;
	}
	

	public Collection getPagingRecords(String hql, Object params,String type,int start,int limit) throws Exception {
		Collection col = null;
		try {
			PageParameter parameter = new PageParameter();
			parameter =  convert.getPageParams(parameter, params);
			IPagination pagination = PaginationFactory.getPaginationInstance();
			int pageNumber = start/limit+1;
			parameter.setPageNumber(pageNumber);
			parameter.setPageSize(limit);
			
			PageResult result = pagination.page(parameter);
			col = result.getSqlResultSet();
			result.clearAll();
		} catch (Exception e) {
			throw new Exception("get paging records error-->"+e.getMessage(),e.getCause());
		}

		return col;
	}
	
	public Collection getRs() {
		return rs;
	}
	public void setRs(Collection rs) {
		this.rs = rs;
	}
	public ListRange getRange() {
		return range;
	}
	public void setRange(ListRange range) {
		this.range = range;
	}
	public BasePara getParavo() {
		return paravo;
	}
	public void setParavo(BasePara paravo) {
		this.paravo = paravo;
	}
	
}
